import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

/**
 * 描述：发送http请求统一服务及上传、下载服务
 * 公司：xxx公司
 * 版权：xxx2020
 * 作者：oyjl
 * 时间：2021-06-07 14:03:12
 */
export class RSendRequestService {
  constructor(public http: HttpClient) { }

  /**
   * 描述：发送GET请求
   * 作者：oyjl
   * 时间：2021-06-07 13:59:03
   */
  public sendRequestByGet(url, options?) {
    return this.http.get(url, options);
  }

  /**
   * 描述：发送POST请求
   * 作者：oyjl
   * 时间：2021-06-07 13:59:03
   */
  public sendRequestByPost(url, body, options?) {
    return this.http.post(url, body, options);
  }

  /**
   * 描述：发送DELETE请求
   * 作者：oyjl
   * 时间：2021-06-07 13:59:03
   */
  public sendRequestByDelete(url, options?) {
    return this.http.delete(url, options);
  }

  /**
   * 描述：发送Request请求
   * 作者：oyjl
   * 时间：2021-06-07 13:59:03
   */
  public sendRequestByRequest(method, url, options?) {
    return this.http.request(method, url, options);
  }

  /**
   * 描述：下载文件
   * 作者：oyjl
   * 时间：2021-06-10 14:08:10
   */
  public downloadFile(url) {
    const a = document.createElement('a');
    a.setAttribute('href', url);
    const event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true);
    a.dispatchEvent(event);
    a.remove();
  }

  /**
   * 描述：上传文件
   * 作者：oyjl
   * 时间：2021-06-10 16:56:55
   */
  public uploadFile($this, url, title) {
    const objE = document.createElement('div');
    objE.innerHTML = `<input type="file"
        accept = "application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">`;
    const input = objE.childNodes[0];
    const event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true);
    input.dispatchEvent(event);
    // @ts-ignore
    // tslint:disable-next-line:space-before-function-paren
    input.onchange = function (e1) {
      const headers = new HttpHeaders();
      headers.set('Content-Type', 'multipart/form-data');
      const fd = new FormData();
      fd.append('upload', this.files[0]);
      $this.dialogService.setProgressBarStatus(true);
      $this.sendRequestService.sendRequestByPost(url, fd, { headers }).subscribe((res: any) => {
        if (res.operateSuccess) {
          $this.commonFun.tipsEject(title, res.opMsg || res.msg, (fun) => {
            $this.getData();
          });
        } else {
          $this.commonFun.tipsEject(title, res.opMsg || res.msg);
        }
        $this.dialogService.setProgressBarStatus(false);
      });
    };
    objE.remove();
  }

  /**
   * 描述：设置多语言缓存数据，便于其他组件做中英文转换
   * 作者：oyjl
   * 时间：2021-07-15 16:57:25
   */
  public setLangCache(lang: any = navigator.language) {
    this.http.get('./assets/i18n/' + lang + '.json').subscribe(data => {
      sessionStorage.setItem('currentLang', JSON.stringify(data));
    });
  }
}
